package dom;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

public class XMLPhoneAddAndDelAndUpd_Dom4j {
    Document doc=null;
    public void getDocument(){
        // 获取解析器工厂
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();

        // 获取解析器
        try {
            SAXReader saxReader=new SAXReader();
            doc=saxReader.read(new File("src/main/resources/savePhoneType.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public void showInfo(){
        // 获取文档的根元素
        Element root=doc.getRootElement();
        // 添加数据
        Element phone = root.addElement("phone");
        phone.addAttribute("name","三星");
        Element type = phone.addElement("type");
        type.addAttribute("name","NoteX");

        // 修改数据

        for (Iterator it=root.elementIterator();it.hasNext();){
            Element element=(Element) it.next();
            String name = element.attributeValue("name");
            if(name.equals("三星")){
                element.addAttribute("name","SAMSUNG");
                break;
            }
        }

        // 数据显示
        for (Iterator iterable = root.elementIterator(); iterable.hasNext();){
            Element brandEle=(Element) iterable.next();

            System.out.println("品牌："+brandEle.attributeValue("name"));
            for (Iterator itType=brandEle.elementIterator();itType.hasNext();){
                Element typeEle=(Element) itType.next();
                System.out.println("\t型号："+typeEle.attributeValue("name"));
            }
        }

//         删除数据
        for (Iterator it=root.elementIterator();it.hasNext();){
            Element element=(Element) it.next();
            String name = element.attributeValue("name");
            if(name.equals("SAMSUNG")){
                root.remove(element);
                break;
            }
        }
       //保存信息
        OutputFormat of= OutputFormat.createPrettyPrint();
        of.setEncoding("UTF-8");
        try {
            XMLWriter writer=new XMLWriter(new FileWriter("src/main/resources/savePhoneType.xml"),of);
            writer.write(doc);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        XMLPhoneAddAndDelAndUpd_Dom4j phoneAddAndDelAndUpd=new XMLPhoneAddAndDelAndUpd_Dom4j();
        phoneAddAndDelAndUpd.getDocument();
        phoneAddAndDelAndUpd.showInfo();
    }
}
